<template>
	<view class="u-page">
		<!-- 🔧 认证加载界面 -->
		<view v-if="isAuthLoading" class="auth-loading-container">
			<view class="loading-content">
				<view class="loading-icon-auth">
					<u-loading-icon mode="spinner" size="60" color="#2979ff"></u-loading-icon>
				</view>
				<text class="loading-title">正在验证身份</text>
				<text class="loading-subtitle">{{ isAuthenticated ? '正在加载培训数据...' : '正在跳转到企业微信授权...' }}</text>
			</view>
			<view class="loading-footer">
				<text class="footer-text">© 2025 中山公交集团会议签到系统</text>
			</view>
		</view>
		
		<!-- 🔧 主要内容区域 - 只有认证成功才显示 -->
		<view v-else>
			<!-- 自定义筛选组件与标题 -->
			<custom-filter 
				:option="option" 
				:option2="option2" 
				:value1="value1" 
				:value2="value2"
				:showStatusDropdown="showStatusDropdown"
				:showOrderDropdown="showOrderDropdown"
				@toggle-status="toggleStatusDropdown"
				@toggle-order="toggleOrderDropdown"
				@select-status="selectStatus"
				@select-order="selectOrder"
			></custom-filter>

			
			<!-- 关闭下拉菜单的点击层 -->
			<view class="overlay" v-if="showStatusDropdown || showOrderDropdown" @click="closeAllDropdowns"></view>
			
			<!-- 空状态 -->
		   <view v-if="list1<1" class="empty-state">
			   <u-empty
			           mode="list"
			           icon="http://cdn.uviewui.com/uview/empty/list.png"	
			   >
			      <text class="empty-text">暂无培训记录</text>
			   </u-empty>
		   </view>
		   
		   <!-- 列表内容 -->
			<view v-else class="list-wrapper">
				<u-list @scrolltolower="scrolltolower">
					<u-list-item v-for="(item, index) in indexList" :key="index">
						<training-card 
							:item="item" 
							:index="index" 
							@view-detail="more"
						></training-card>
					</u-list-item>
					
					<!-- 加载更多提示 -->
					<view class="loading-more">
						<view v-if="isLoading" class="loading-icon"></view>
						<text class="load-text">{{isLoading ? '加载中...' : '上拉加载更多'}}</text>
					</view>
				</u-list>
			</view>
		</view>
	</view>
</template>

<script>
import indexList from '../../uni_modules/uview-ui/libs/config/props/indexList';
import { onLoad } from '../../uni_modules/uview-ui/libs/mixin/mixin';
import { mapGetters } from 'vuex';
import TrainingCard from './components/TrainingCard.vue';
import CustomFilter from './components/CustomFilter.vue';
import authMixin from '@/mixins/authMixin.js';

	export default {
	name: 'TrainingList',
	mixins: [authMixin],
	components: {
		// 显式引入组件
		TrainingCard,
		CustomFilter
	},
	data() {
		return {
			indexList: [],
			option: [{
					text: '全部',
					value: ''
				},
				{
					text: '未开始',
					value: 0
				},
				{
					text: '进行中',
					value: 1
				},
				{
					text: '已结束',
					value: 2
				},
				// {
				// 	text: '未开始',
				// 	value: 3
				// },
				
			],
			option2: [{
					text: '日期降序',
					value: "u.create_time desc"
				},
				{
					text: '日期升序',
					value: "u.create_time asc"
				},
			],
			value1: '',
			value2: '',
			value6:0,
			page:0,
			list1:1,
			isLoading: false,
			showStatusDropdown: false,
			showOrderDropdown: false,
			isAuthLoading: true, // 🎯 认证加载状态
		}
	},
	
	computed: {
		// 🎯 获取认证状态
		...mapGetters([
			'isAuthenticated'
		])
	},
		
	async onLoad(option) {
		// 🎯 页面一开始就显示loading，不显示任何内容
		console.log("🔍 培训列表页面加载，开始认证检查...");
		
		// 🎯 使用直接认证检查，避免显示主页
		const authResult = await this.performDirectAuth(() => {
			// 认证成功回调 - 关闭认证加载状态，加载数据
			console.log("✅ 培训列表认证成功，加载数据");
			this.isAuthLoading = false;
			this.loadmore();
		}, () => {
			// 认证失败回调 - 用户将被跳转到认证页面，保持loading状态
			console.log("❌ 培训列表认证失败，将跳转认证");
			// 不要设置 isAuthLoading = false，因为用户会被跳转走
		});
		
		// 🔧 如果认证失败，用户会被跳转，这里不会执行
		console.log("🔍 认证检查完成，结果:", authResult);
	},
		onShow: function() {
		            uni.$once('query' ,(query)=>{
						//console.log();
						this.indexList[query.index].condition=1;
		            });
		        },
		// onShow(){
		// 	this.loadmore();
		// 	},
		mounted() {
			this.value1 = this.option[0]['value'];
			this.value2 = this.option2[0]['value'];
			// alert(this.list1);
		},
		methods: {
			more(index, teachId, item) {
				// 🔧 跳转到培训详情页面，传递培训ID
				uni.navigateTo({
					url: `/pages/dtest/detail?teach_id=${teachId}&index=${index}&teach_name=${encodeURIComponent(item.teach_name || '培训详情')}`
				});
			},
		// 获取当前状态文本
		getStatusText() {
			for(let item of this.option) {
				if(item.value === this.value1) {
					return `状态：${item.text}`;
				}
			}
			return '状态：全部';
		},
		// 获取当前排序文本
		getOrderText() {
			for(let item of this.option2) {
				if(item.value === this.value2) {
					return `排序：${item.text}`;
				}
			}
			return '排序：日期降序';
		},
		// 选择状态
		selectStatus(item) {
			console.log('选择状态:', item.text);
			this.value1 = item.value;
			this.showStatusDropdown = false;
			this.search();
		},
		// 选择排序
		selectOrder(item) {
			console.log('选择排序:', item.text);
			this.value2 = item.value;
			this.showOrderDropdown = false;
			this.search();
		},
		// 关闭所有下拉菜单
		closeAllDropdowns() {
			console.log('关闭所有下拉菜单');
			this.showStatusDropdown = false;
			this.showOrderDropdown = false;
		},
		// 切换状态下拉菜单
		toggleStatusDropdown() {
			console.log('切换状态筛选:', !this.showStatusDropdown);
			this.showStatusDropdown = !this.showStatusDropdown;
			if (this.showStatusDropdown) {
				this.showOrderDropdown = false;
			}
		},
		// 切换排序下拉菜单
		toggleOrderDropdown() {
			console.log('切换排序筛选:', !this.showOrderDropdown);
			this.showOrderDropdown = !this.showOrderDropdown;
			if (this.showOrderDropdown) {
				this.showStatusDropdown = false;
			}
		},
			change1(item) {
				// alert(this.value1);
				console.log(item);
				this.search();
				// alert(123);
			},
			change2(item) {
				// alert(this.indexList.length);
				console.log(item);
				if(this.indexList.length>0){
		
				   this.search()	
				}
				
			},
			scrolltolower() {
				this.loadmore()
			},
			search(){
				
				this.page=0;
				if(this.indexList.length>0){
					this.indexList=[]
				}
			//this.indexList=[];
				this.loadmore()
			},
			loadmore() {
				if(this.value2==""){
					this.value2="u.create_time desc";
				}
			
			this.isLoading = true;
				this.page++;
				var page = this.page;
				var limit = 5;
				
				const apiUrl = this.$store.getters.getApiUrl('v2')+'/teach-list?limit='+limit+'&page='+page+"&userid="+this.userid+"&teach_condition="+this.value1+"&order="+this.value2;
				
				uni.$u.http.get(apiUrl).then(res => {
				this.isLoading = false;
				
					if(res.data.status==1){
						 	let arr = res.data.data;
						 	// 🔧 后端已经使用GROUP BY处理重复问题，前端直接添加数据
						 	for(let item of arr){
								this.indexList.push(item);
						 	}
						 	this.list1=1;
						 }else{
							 if(this.indexList.length<1){
								 this.list1=0;
							 }else{
								 this.page--;
								 this.list1=1;
							 }
						 }
				}).catch(err => {
				this.isLoading = false;
				console.error('请求失败:', err);
				uni.showToast({
					title: '请求失败: ' + (err.message || '网络错误'),
					icon: 'none',
					duration: 3000
				});
				})
			
				// for (let i = 0; i < 30; i++) {
				// 	this.indexList.push()
				// }
			},
			listdetail(index){
				alert(index);
			},
		}
	}
</script>

<style lang="scss">
.u-page {
	background-color: #f5f7fa;
	min-height: 100vh;
	padding-bottom: 30rpx;
}

.overlay {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0,0,0,0.02);
	z-index: 90;
	animation: fadeIn 0.2s ease-out forwards;
}

@keyframes fadeIn {
	from {
		opacity: 0;
	}
	to {
		opacity: 1;
	}
}

.empty-state {
	padding: 100rpx 0;
	display: flex;
	flex-direction: column;
	align-items: center;
	position: relative;
	z-index: 1;
}

.empty-text {
	font-size: 28rpx;
	color: #909399;
	margin-top: 20rpx;
}

.list-wrapper {
	padding: 20rpx;
	position: relative;
	z-index: 1;
	border-radius: 16rpx;
}

.loading-more {
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 30rpx 0;
}

.loading-icon {
	width: 28rpx;
	height: 28rpx;
	border: 3rpx solid transparent;
	border-top-color: #2979ff;
	border-radius: 50%;
	animation: spin 0.8s linear infinite;
}

@keyframes spin {
	0% { transform: rotate(0deg); }
	100% { transform: rotate(360deg); }
}

.load-text {
	font-size: 26rpx;
	color: #909399;
	margin-left: 10rpx;
}

/* 统一卡片样式 */
:deep(.info-card) {
	background-color: #ffffff;
	border-radius: 16rpx;
	margin-bottom: 24rpx;
	overflow: hidden;
	box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
	position: relative;
}

:deep(.card-header) {
	display: flex;
	justify-content: flex-start;
	align-items: center;
	padding: 20rpx 24rpx;
	background: linear-gradient(to right, #fbfcff, #f9fbff);
	border-bottom: 1px solid #f1f3f7;
}

:deep(.header-icon) {
	width: 44rpx;
	height: 44rpx;
	background-color: #2979ff;
	border-radius: 22rpx;
	display: flex;
	justify-content: center;
	align-items: center;
	margin-right: 16rpx;
}

:deep(.card-title) {
	font-size: 30rpx;
	font-weight: 600;
	color: #303133;
}

:deep(.info-list) {
	padding: 24rpx;
}

:deep(.info-item) {
	display: flex;
	align-items: center;
	margin-bottom: 20rpx;
}

:deep(.item-icon) {
	width: 36rpx;
	height: 36rpx;
	margin-right: 16rpx;
	position: relative;
}

:deep(.item-content) {
	flex: 1;
}

:deep(.item-label) {
	font-size: 26rpx;
	color: #909399;
	margin-bottom: 4rpx;
}

:deep(.item-value) {
	font-size: 30rpx;
	color: #303133;
	font-weight: 500;
}

/* 统一图标样式 */
:deep(.title-icon),
:deep(.type-icon),
:deep(.time-icon),
:deep(.location-icon),
:deep(.content-icon) {
	background-color: rgba(0, 0, 0, 0.04);
	border-radius: 6rpx;
}

/* 🔧 认证加载界面样式 - 与home.vue保持一致 */
.auth-loading-container {
	min-height: 100vh;
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	background-color: #f7f9fc;
}

.loading-content {
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 60rpx 40rpx;
	background-color: #ffffff;
	border-radius: 20rpx;
	box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.08);
	margin: 40rpx;
}

.loading-icon-auth {
	margin-bottom: 40rpx;
}

.loading-title {
	font-size: 32rpx;
	font-weight: 600;
	color: #303133;
	margin-bottom: 16rpx;
	text-align: center;
}

.loading-subtitle {
	font-size: 26rpx;
	color: #909399;
	text-align: center;
	line-height: 1.5;
	max-width: 400rpx;
}

.loading-footer {
	margin-top: auto;
	padding: 40rpx 0 20rpx;
}

.footer-text {
	font-size: 24rpx;
	color: #909399;
}
</style>